package com.gjintel.framework.dept.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.cache.InitCacheData.CacheType;
import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.constant.Constant.RightType;
import com.gjintel.framework.dept.model.Dept;
import com.gjintel.framework.dept.service.IDeptService;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.log.util.LogUtil.LogType;
import com.gjintel.framework.role.service.IRoleService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.user.service.IUserService;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.dto.TreeDto;
import com.gjintel.sdk.util.StringUtil;

@RequestMapping("/framework/dept")
@Controller
public class DeptController {
	private static final Logger LOG = Logger.getLogger(DeptController.class);
	@Autowired
	private IDeptService deptService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IRoleService roleService;
	
	/**
	 * @description 根据ID对当前的操作进行控制（ID为空，代表当前是添加操作，ID不为空，代表当前是更新操作）
	 * @author fengya
	 * @date 2015-7-23 上午10:54:10
	 * @param id
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/input")
	public ModelAndView input(String id) {
		ModelAndView mv = new ModelAndView("/framework/dept/dept-input");
		Dept dept = null;
		if (!StringUtil.isEmpty(id)) {
			dept = (Dept) InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(id);
			if (!StringUtil.isEmpty(dept.getPid())) {
				Object obj = InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(dept.getPid());
				if (obj != null) {
					Dept pDept = (Dept) obj;
					dept.setpName(pDept == null ? "" : pDept.getName());
				}
			}
			mv.addObject("dept", dept);
		}
		return mv;
	}

	@RequestMapping("/index")
	public ModelAndView index(HttpSession session) {
		ModelAndView mv = new ModelAndView("/framework/dept/dept");
		User sUser = (User) session.getAttribute("loginUser");
//		String userRightData = this.userService.getUserRightData(sUser.getId());
//		if (userRightData.contains(RightType.SAME_LEVEL_USER.toString().toLowerCase()) || sUser.getId().equals("1")) {
//			mv.addObject("isRight", true);
//		}
		boolean isRight=this.roleService.isPrivilege(sUser.getId(), ActivitiMap.ADMINISTRATOR_ID);
		if(isRight||sUser.getId().equals("1")){//系统管理员或admin
			mv.addObject("isRight", true);
		}
		return mv;
	}

	/**
	 * @方法名：getDeptTree
	 * @功能说明：得到机构树
	 * @author fengya
	 * @date 2014-4-26 下午04:07:36
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getDeptTreeDialog")
	@ResponseBody
	public JSONObject getDeptTreeDialog(HttpSession session, String id, String nodeName, String deleteIds) {
		User sUser = (User) session.getAttribute("loginUser");
		Dept loginDept = (Dept) InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(sUser.getDeptId());
		// 树中节点所在的集合
		List<TreeDto> treeList = new ArrayList<TreeDto>();
		try {
			if (nodeName != null) {
				nodeName = URLDecoder.decode(nodeName, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			LOG.debug("汉字转换错误！", e);
		}
		Map jsonData = new HashMap();
		boolean isRoot = false;
		if (StringUtil.isEmpty(id)) {
			id = loginDept.getpUnit();
			isRoot = true;
		}
		boolean isManager = false;
		if (sUser.getId().equals("1")) {
			isManager = true;
		}
		List<String> selIds = this.deptService.getDeptTree(treeList, id, nodeName, deleteIds, false, isRoot, isManager);
		jsonData.put("selIds", JSONArray.fromObject(selIds));
		jsonData.put("tree", JSONArray.fromObject(treeList));
		return JSONObject.fromObject(jsonData);
	}

	@RequestMapping("/getDeptTree")
	@ResponseBody
	public JSONArray getDeptTree(HttpSession session, String id) {
		User sUser = (User) session.getAttribute("loginUser");
		Dept loginDept = (Dept) InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(sUser.getDeptId());
		List<TreeDto> treeList = new ArrayList<TreeDto>();
		boolean isManager = false;
		if (sUser.getId().equals("1")) {
			isManager = true;
		}
		if (StringUtil.isEmpty(id) && !sUser.getId().equals("1")) {
			id = loginDept.getpUnit();
			this.deptService.getDeptTree(treeList, id, null, null, false, true, isManager);
		} else {
			// 树中节点所在的集合
			this.deptService.getDeptTree(treeList, id, null, null, false, false, isManager);
		}
		return JSONArray.fromObject(treeList);
	}

	/**
	 * @方法名：list
	 * @功能说明：根据查询条件获得消息类型记录
	 * @author fengya
	 * @date 2014-5-30 下午04:39:36
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/list")
	@ResponseBody
	public JSONObject list(HttpSession session, Page page, Dept dept, Sort sort) {
		User sUser = (User) session.getAttribute("loginUser");
		int loginUserType = 0;
		// String loginUserDeptUnit = null;
		if (sUser.getId().equals("1")) {
			loginUserType = 1;
		}
		Dept loginDept = (Dept) InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(sUser.getDeptId());
		this.deptService.findAll(page, dept, sort, loginUserType, loginDept.getpUnit(), sUser.getDeptId());
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description 得到登录人所属的单位下所有的子部门信息
	 * @author fengya
	 * @date 2016-4-1 上午09:17:05
	 * @param loginUserDeptId
	 * @return
	 * @return String
	 */
	// private String getLoginUserUnitIds(String loginUserDeptId){
	// List<String> deptIds = new ArrayList<String>();
	// this.setLoginUserUnitIds(loginUserDeptId, deptIds);
	// StringBuilder userDeptUnit = new StringBuilder();
	// for(int i=0;i<deptIds.size();i++){
	// if(i == 0){
	// userDeptUnit.append("\'").append(deptIds.get(i)).append("\'");
	// } else {
	// userDeptUnit.append(",").append("\'").append(deptIds.get(i)).append("\'");
	// }
	// }
	// return userDeptUnit.toString();
	// }

	/**
	 * @description 得到所有的子部门ID
	 * @author fengya
	 * @date 2016-4-1 上午09:22:02
	 * @param pDeptId
	 * @param deptIds
	 * @return void
	 */
	private void setLoginUserUnitIds(String pDeptId, List<String> deptIds) {
		List<Object> loginDeptList = InitCacheData.getInstance().getCacheTreeData(CacheType.DEPT).get(pDeptId);
		if (loginDeptList != null) {
			Dept dept = null;
			for (Object obj : loginDeptList) {
				dept = (Dept) obj;
				deptIds.add(dept.getId());
				this.setLoginUserUnitIds(dept.getId(), deptIds);
			}
		}
	}

	/**
	 * @方法名：save
	 * @功能说明：保存记录数据
	 * @author fengya
	 * @date 2014-5-30 上午09:28:49
	 * @return void
	 * @throws Exception
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(HttpSession session, Dept dept) {
		User user = (User) session.getAttribute("loginUser");
		boolean sign = false;
		boolean flag = false;
		if (dept != null) {
			if (StringUtil.isEmpty(dept.getId())) {
				dept.setId(null);
				dept.setCreateTime(new Date());
				dept.setCreaterId(user.getId());
				dept.setCreaterName(user.getName());
				flag = true;
			}
			if (dept.getType().equals(Constant.DEPT_TYPE_DEPT)) {
				Dept temp = (Dept) InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(dept.getPid());
				while (temp.getType().equals(Constant.DEPT_TYPE_DEPT)) {
					temp = (Dept) InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(temp.getPid());
				}
				dept.setpUnit(temp.getId());
				sign = true;
			}
			dept.setUpdateTime(new Date());
			dept.setUpdaterName(user.getName());
			dept.setUpdaterId(user.getId());
			this.deptService.saveOrUpdate(dept);
			if (!sign) {
				dept.setpUnit(dept.getId());
				this.deptService.saveOrUpdate(dept);
			}
			InitCacheData.getInstance().initDeptData();
			if (flag) {
				LogUtil.addLog(new LogInfo("添加部门信息", user.getId(), user.getName(), String.valueOf(LogType.ADD.ordinal()), dept.getClass().getSimpleName(), dept.getId()));
			} else {
				LogUtil.addLog(new LogInfo("更新部门信息", user.getId(), user.getName(), String.valueOf(LogType.UPDATE.ordinal()), dept.getClass().getSimpleName(), dept.getId()));
			}
			return Constant.SAVE_SUCCESS;
		}
		return Constant.SAVE_UN_SUCCESS;
	}

	/**
	 * @方法名：remove
	 * @功能说明：根据选择的记录进行删除数据
	 * @author fengya
	 * @date 2014-4-17 下午04:13:04
	 * @return void
	 * @throws Exception
	 */
	@RequestMapping("/remove")
	@ResponseBody
	public String remove(HttpSession session, String deleteIds) {
		User user = (User) session.getAttribute("loginUser");
		this.deptService.removeData(deleteIds,user);
		InitCacheData.getInstance().initDeptData();
		return Constant.DEL_SUCCESS;
	}

	/**
	 * @description 通过选择的node节点，获取部门信息
	 * @author xiapin
	 * @date 2016-3-30 下午01:17:27
	 * @return mv
	 */
	@RequestMapping("/getDeptType")
	public ModelAndView getDeptType(String id) {
		ModelAndView mv = new ModelAndView("/framework/dept/dept-type");
		Object obj = InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(id);
		Dept dept = null;
		if (obj != null) {
			dept = (Dept) obj;
		}
		mv.addObject("dept", dept);
		return mv;
	}
}
